package com.um.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.um.entity.Result;
import com.um.entity.UserEntity;
import com.um.entity.UserRoleEntry;
import com.um.mapper.UserMapper;
import com.um.mapper.UserRoleMapper;
import com.um.utils.ResultEnum;
import com.um.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("/base")
public class BaseController {

    @Autowired
    UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper ;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping(value = "/logon")
    public Result logon(String username, String password, String email) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserEntity selectUser = userMapper.selectOne(queryWrapper);
        if (null == selectUser) {
            if (userMapper.selectOne(new QueryWrapper<UserEntity>().eq("email", email)) != null) {
                return ResultUtil.error(ResultEnum.EMAIL_IS_ERROR.getCode(), ResultEnum.EMAIL_IS_ERROR.getMsg());
            }
            UserEntity userEntity = new UserEntity();
            userEntity.setUsername(username);
            userEntity.setFullname(username);
            userEntity.setEmail(email);
            userEntity.setPassword(passwordEncoder.encode(password));
            userMapper.insert(userEntity);
            Integer userId = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("email", email)).getId() ;
            UserRoleEntry userRoleEntry = new UserRoleEntry() ;
            userRoleEntry.setUserId(userId);
            userRoleEntry.setRoleId(1);
            userRoleMapper.insert(userRoleEntry) ;
            return ResultUtil.success();
        }
        return ResultUtil.error(ResultEnum.USER_IS_ERROR.getCode(), ResultEnum.USER_IS_ERROR.getMsg());
    }

    /**
     * 登陆方法，调用鉴权服务实现登陆并返回token
     *
     * @param email    邮箱
     * @param password 密码
     * @return
     */
    @PostMapping(value = "/login")
    public Result login(String email, String password) {
        String username ;
        try {
            username = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("email", email)).getUsername();
        }catch (NullPointerException e){
            return ResultUtil.error(ResultEnum.USER_LOGIN_ERROR.getCode(),ResultEnum.USER_LOGIN_ERROR.getMsg()) ;
        }
        /**
         * 请求鉴权服务，完成登陆并获取token
         */
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("username", username);
        params.add("password", password);
        params.add("grant_type", "password");
        params.add("client_id", "c1");
        params.add("client_secret", "secret");
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(params,headers) ;
        JSONObject json ;
        try {
            json= restTemplate.exchange("http://B-OAUTH-SERVICE/oauth/token", HttpMethod.POST,request,JSONObject.class).getBody();
        }catch (Exception e){
            return ResultUtil.error(ResultEnum.USER_LOGIN_ERROR.getCode(),ResultEnum.USER_LOGIN_ERROR.getMsg()) ;
        }
        if (!json.containsKey("access_token")){
            return ResultUtil.error(ResultEnum.USER_LOGIN_ERROR.getCode(),ResultEnum.USER_LOGIN_ERROR.getMsg()) ;
        }
        return ResultUtil.success(json);
    }

}
